﻿var maxPage = 0;
var index = 0;

var isLoading = false;
var isLoadingAllow = true;
var pageUrl = "";

$(function () {
    maxPage = $('#productList').attr("data-pageCount");
    index = $('.item:last').attr("data-pageIndex");

    registerEvent();
    pageUrl = document.location.pathname;
    $(window).scroll(function () {
        if ($(window).scrollTop() >= $(document).height() - $(window).height() - 200) {
            if (!isLoading && isLoadingAllow)
                loadContent();
        }
    });

});

function loadContent() {
    if (++index > maxPage) {
        isLoadingAllow = false;
        return;
    }
    
    isLoading = true;
    $('#loading').show();
    $('#pageLabel').text(index);
    var url = "";
    if (pageUrl.indexOf("?page") > 0) {
        url = pageUrl.split("?")[0] + "?page=" + index;
    } else {
        url = pageUrl + "?page=" + index;
    }
    $.get(url, function (data) {
        $('#productList').append("<div class='page'>Trang " + index + "</div>");
        $('#productList').append(data);
        registerEvent();
        $('#loading').hide();
        isLoading = false;
    });
}
var registerEvent = function () {
    $("img.lazy").show().lazyload();
    $(".item").off();
    $("a.viewzoom").off();

    $(".item").on('mouseout', function () {
        $('a.viewzoom', this).css('display', 'none');
    });

    $(".item").on('mouseover', function () {
        $('a.viewzoom', this).css('display', 'block');
    });

    $("a.viewzoom").on('click', function () {
        var src = $(this).attr('href');
        //alert(src);
        var previewDialog = $('<iframe id="editDialogAddCard" frameborder="0" src="' + src + '" />').dialog({
            closeText: "", width: 850, height: 440, modal: true, close: function () {
                try {
                    previewDialog.remove();
                    //endLoading();
                } catch (err) { }
            }
        }).width(850).height(440);
        return false;
    });
}